package com.jame.aop;

import com.jame.typeenum.AccessModifier;
import com.jame.typeenum.AnnotationType;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;


/**
 * @author : Jame
 * @date : 2021-07-02 14:20
 * 进行增强的类使用cglib
 **/
public class ProxyFactory implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    private List<AopResult> aopResults;


    public Object getProxy(Class clazz, List<AopResult> aopResult) {
        this.aopResults = aopResult;
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    /**
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object result ;
        for (AopResult aopResult : aopResults) {
            ExecuteClassParticulars e = aopResult.getExecuteClassParticulars();
            if (aopResult.getAnnotationType() == AnnotationType.Before ||
                    aopResult.getAnnotationType() == AnnotationType.Around) {
                //验证是否符合表达式
                if (verificationModifier(e, method)) {
                    aopResult.getMethod().invoke(aopResult.getInstance(), objects);
                }
            }
        }
        result = methodProxy.invokeSuper(o, objects);

        for (AopResult aopResult : aopResults) {
            ExecuteClassParticulars e = aopResult.getExecuteClassParticulars();
            if (aopResult.getAnnotationType() == AnnotationType.After ||
                    aopResult.getAnnotationType() == AnnotationType.Around) {
                //验证是否符合表达式
                if (verificationModifier(e, method)) {
                    aopResult.getMethod().invoke(aopResult.getInstance(), objects);
                }
            }
        }
        return result;
    }

    /**
     * 验证修饰符
     * @param e
     * @param m
     * @return
     */
    private boolean verificationModifier(ExecuteClassParticulars e, Method m) {
        if(m.getName().equals("toString")||m.getName().equals("hashCode"))
            return false;
        return (e.getMethodName().equals("*") || e.getMethodName().equals(m.getName())) &&
                (e.getReturnType().equals("*") || e.getReturnType().equals(m.getReturnType().getSimpleName())) &&
                (e.getAccessModifier() == AccessModifier.All || e.getAccessModifier().getCode() == m.getModifiers());
    }


}
